package com.phone.handle;

import com.phone.entity.History;
import com.phone.entity.Invite;
import com.phone.exception.*;
import org.hibernate.Session;

import java.util.Date;
import java.util.List;

/**
 * Created by tisen on 2017/8/7.
 */
public class InviteHandle {
    private Session session;

    public InviteHandle(Session session) {
        this.session = session;
    }

    public void setSession(Session session) {
        this.session = session;
    }

    public Session getSession() {
        return session;
    }

    public String save(String inviterid, String invitedid) throws Exception {
        UserHandle userHandle = new UserHandle(session);
        if (!userHandle.checkId(inviterid))
            throw new ErrorInviteridException();
        if (!userHandle.checkId(invitedid))
            throw new ErrorInvitedidException();
        if (checkIdInvited(invitedid))
            throw new UserInvitedException();
        Invite invite = new Invite();
        invite.setInviterid(inviterid);
        invite.setInvitedid(invitedid);
        return (String) session.save(invite);
    }

    public Invite get(String id) throws Exception {
        Invite invite = session.get(Invite.class, id);
        if (invite == null)
            throw new NoBindingIdException();
        return invite;
    }

    public boolean checkIdInvited(String invitedid) throws Exception {
        List<Invite> invites = session.createQuery("from Invite where invitedid= '" + invitedid + "'").list();
        if (invites == null || invites.isEmpty()) {
            return false;
        } else {
            return true;
        }
    }

    public List<Invite> search(String inviterid) throws Exception {
        return session.createQuery("from Invite where inviterid= '" + inviterid + "'").list();
    }
}
